import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, ActivityIndicator, ScrollView } from 'react-native';
import { Icon, List, ListItem, Button } from 'react-native-elements';
import { primaryColor, executor, toast } from './utils';
import OrderListItem from './components/OrderListItem';
import Loader from './widgets/Loader';

const styles = StyleSheet.create({
  button: {
    margin: 16,
  }
});

class CollectOrderPage extends Component {
  static navigationOptions = ({screenProps, navigation}) => {
    return {
      title: `Collect #${navigation.state.params.displayId}`,
    };
  }
  state = {}
  onCollect = () => {
    const unchecked = this.props.order.pricing.details.filter(item =>
      !this.state[item.productId]).map(item => `${item.description} x ${item.quantity}`);
    if (unchecked.length>0) return toast(`Unchecked items:\n${unchecked.join('\n')}`);

    executor(this.props.collectOrder, this.props.order.pricing.details.map(({description, quantity}) => `${description} x ${quantity}`).join(', '))
      .then(({res}) => {
        if (res) {
          toast('Collect success');
          this.props.navigation.goBack();
        } else {
          this.setState({submitting: false})
        }
      })
    this.setState({submitting: true});
  }
  render() {
    const { order, loading } = this.props;
    if (!order||loading) return <Loader/>;

    return (
      <ScrollView>
        <List>
          {
            order.pricing.details.map((item, index) =>
              <ListItem key={index} avatar={{uri:item.imageUrl}} roundAvatar onPress={()=>this.setState({[item.productId]: true})}
                title={item.description} subtitle={`x ${item.quantity} ${item.quantityUnit}`}
                rightIcon={{name: this.state[item.productId]?'check-box':'check-box-outline-blank', color: this.state[item.productId]?primaryColor:null}}/>)
          }
        </List>
        {this.state.submitting?<ActivityIndicator style={styles.button}/>:<Button style={styles.button} title='COLLECT' backgroundColor={primaryColor} onPress={this.onCollect}/>}
      </ScrollView>
    );
  }
}

export default compose(
  graphql(gql`
    query CollectOrderPage($orderId:String!) {
      order(id:$orderId) {
        id
        pricing {
          details {
            productId
            imageUrl
            description
            quantity
            quantityUnit
          }
        }
      }
    }
  `, {
    options: ({navigation}) => {
      return {
        variables: {
          orderId: navigation.state.params.orderId
        }
      }
    },
    props: ({data:{order, loading}}) => {
      return {
        order,
        loading
      };
    }
  }),
  graphql(gql`
    mutation collectOrder($orderId:String!,$content:String) {
      collectOrder(orderId:$orderId,content:$content) {
        id
        storages
        ...OrderListItem
      }
    }
    ${OrderListItem.fragments.order}
  `, {
    props: ({ownProps:{navigation:{state:{params:{orderId}}}}, mutate}) => {
      return {
        collectOrder: (content) => mutate({
          variables: {
            orderId,
            content
          }
        })
      };
    }
  })
)(CollectOrderPage);

